package cn.cqie.attendance.common.service.impl;

import cn.cqie.attendance.common.pojo.Attachment;
import cn.cqie.attendance.common.dao.AttachmentMapper;
import cn.cqie.attendance.common.service.AttachmentService;
import cn.cqie.attendance.common.util.DateUtil;
import cn.cqie.attendance.common.util.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author FallInLove
 * @since 2021-06-16
 */
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements AttachmentService {

    @Autowired
    AttachmentMapper attachmentMapper;

    @Value("${attachmentFilePath}")
    String path;

    @Autowired
    HttpServletRequest request;

    @Override
    @Transactional
    public Page upload(MultipartFile[] files, Integer type, Integer homeworkId,
                       Integer leaveId, Integer publishHomeworkId) {
        if (files.length <= 0) {
            return Page.SUCCESS;
        }
        if ( null == homeworkId && null == leaveId && publishHomeworkId == null
                || null != homeworkId && null != leaveId && null != publishHomeworkId || type == null) {
            return Page.FAIL;
        }
        String filename;
        try {
            String path = this.path + DateUtil.getNowFormatDate("yyyyMMddHHmmssSSS")
                    + (new Random().nextInt(10000)) + "/";
            new File(path).mkdirs();
            for (MultipartFile file : files) {
                filename = path + file.getOriginalFilename();
                attachmentMapper.insert(new Attachment(filename, type, leaveId, homeworkId, publishHomeworkId));
                file.transferTo(new File(filename));
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
            return Page.EXCEPTION;
        }
        return Page.SUCCESS;
    }

    @Override
    @Transactional
    public Page update(MultipartFile[] files, Integer type, Integer homeworkId, Integer leaveId, Integer publishHomeworkId) {
        if ( null == homeworkId && null == leaveId && publishHomeworkId == null
                || null != homeworkId && null != leaveId && null != publishHomeworkId) {
            return Page.FAIL;
        }
        List<Attachment> attachments = attachmentMapper.queryAttachment(homeworkId, leaveId, publishHomeworkId);
        String filePath = "";
        if (!attachments.isEmpty()) {
            filePath = attachments.get(0).getAddress();
            filePath = filePath.substring(0, filePath.lastIndexOf("/"));
            File f = new File(filePath);
            if (f.isDirectory()) {
                File[] fileList = f.listFiles();
                if (fileList != null) {
                    for (File file : fileList) {
                        file.delete();
                    }
                }
            }
        }
        for (Attachment attachment : attachments) {
            attachmentMapper.deleteAttachment(attachment.getId());
        }
        if (files.length != 0) {
            try {
                for (MultipartFile file : files) {
                    String path = filePath + file.getOriginalFilename();
                    attachmentMapper.insert(new Attachment(path,
                            type, leaveId, homeworkId, publishHomeworkId));
                    file.transferTo(new File(path));
                }
            } catch (IOException e) {
                e.printStackTrace();
                return Page.EXCEPTION;
            }
        }
        return Page.SUCCESS;
    }

    @Override
    public ResponseEntity<FileSystemResource> download(String path) {
        return export(new File(path));
    }

    private ResponseEntity<FileSystemResource> export(File file) {
        if (file == null || !file.exists()) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + file.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }

}
